package com.wgo.bpot.server.web.util;

import java.text.MessageFormat;
import java.util.Collections;
import java.util.List;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;


public class PropertyAccessor {
    private static final String BUNDLE_NAME = "server"; //$NON-NLS-1$

    public static final ResourceBundle RESOURCE_BUNDLE;
    
    private static transient final Logger log = Logger.getLogger(PropertyAccessor.class);

    static {
        RESOURCE_BUNDLE = PropertyResourceBundle.getBundle(BUNDLE_NAME);
    }
    
    private PropertyAccessor() {
    }

    public static String getString(String key) {
    	String result = null;
        try {
        	result = RESOURCE_BUNDLE.getString(key);
        } catch (Exception e) {
        	log.warn("Failed retrieving string value for key: " + key);
        }
        return result;
    }

    public static String getFormattedString(String key, Object arg) { 
        String format= null; 
        try { 
            format= RESOURCE_BUNDLE.getString(key); 
        } catch (MissingResourceException e) { 
            return "!" + key + "!";
        } 
        if (arg == null) 
            arg= ""; 
        return MessageFormat.format(format, new Object[] { arg }); 
    }
    
    public static String getFormattedString (String key, String[] args) { 
        return MessageFormat.format(RESOURCE_BUNDLE.getString(key), new Object[] {args}); //TODO: test if this works, else use next line 
//        return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args); 
    }
        
    /**
     * Used to give hibernate the settings needed top connect to database.
     * 
     * @return the properties from the properties-file
     */
    public static Properties retrieveDatabaseConfiguration() {
        Properties hibernateProperties = new Properties();
        List<String> keys = Collections.list(RESOURCE_BUNDLE.getKeys());
        for ( String key : keys ) {
            if (key.indexOf("hibernate.") == 0) {
                String value = getString(key);
                hibernateProperties.put(key, value);
                log.debug("Created Hibernate-property: " + key + " , value: " + value);
            }
        }
        return hibernateProperties;
    }

}
